﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using DevExpress.XtraBars;

namespace PRE.Catalog
{
    /// <summary>
    /// Author:		Nguyen Van Toan
    /// Email:		nvt87x@gmail.com
    /// Phone:		01645 515 010
    /// Create:		19/02/2012 08:00 AM
    /// Update:		?
    /// Lease form: management lease for room of guests
    /// </summary>
    public partial class FrmLease : PRE.Catalog.FrmBase
    {
        private const string STR_ADD = "Thêm thuê phòng";
        private const string STR_EDIT = "Sửa thuê phòng";
        private const string STR_DELETE = "Xoá thuê phòng";

        private const string STR_SELECT = "Chọn dữ liệu!";
        private const string STR_CONFIRM = "Có xoá thuê phòng này không?";
        private const string STR_UNDELETE = "Không xoá được!\nDữ liệu đang được sử dụng.";
        private const string STR_DUPLICATE = "Tên này có rồi";
        private const string STR_EMPTY = "Chưa nhập [{0}]";
        private const string STR_FULL = "Đã hết phòng cho thuê!";

        readonly BLL.GuestBLL _gst = new BLL.GuestBLL();
        readonly BLL.FeeBLL _fee = new BLL.FeeBLL();
        readonly BLL.RoomBLL _roo = new BLL.RoomBLL();
        readonly BLL.LeaseTypeBLL _typ = new BLL.LeaseTypeBLL();

        public FrmLease()
        {
            InitializeComponent();

            grvMain.OptionsBehavior.Editable = false;
            bbiAdd.Visibility = BarItemVisibility.Never;
            _bll = new BLL.LeaseBLL();
        }

        private void FrmLease_Load(object sender, EventArgs e)
        {
            lokGuestId.Properties.DataSource = _gst.Select();
            lokLeaseTypeId.Properties.DataSource = _typ.Select();

            lokGuestId.ItemIndex = 0; // none
            lokRoomId.ItemIndex = 0; // none
            lokLeaseTypeId.ItemIndex = 0; // none
        }

        #region Override
        /// <summary>
        /// Perform when click add button
        /// </summary>
        protected override void PerformAdd()
        {
            base.PerformAdd();
        }

        /// <summary>
        /// Perform when click cancel button
        /// </summary>
        protected override void PerformCancel()
        {
            base.PerformCancel();
        }

        /// <summary>
        /// Perform when click delete button
        /// </summary>
        /// <returns></returns>
        protected override void PerformDelete()
        {
            var tmp = grvMain.GetFocusedRowCellValue("Id") + "";
            long id = UTL.Number.ToInt64(tmp);

            if (id == 0) UTL.Message.Show(STR_SELECT, STR_DELETE);
            else
            {
                var oki = UTL.Message.Show(STR_CONFIRM, STR_DELETE, MessageBoxButtons.OKCancel);

                if (oki == DialogResult.OK)
                    if (_bll.Delete(id) == UTL.Session.PerState.Success) PerformRefresh();
                    else UTL.Message.Show(STR_UNDELETE, STR_DELETE);
            }

            base.PerformDelete();
        }

        /// <summary>
        /// Perform when click edit button
        /// </summary>
        protected override void PerformEdit()
        {
            base.PerformEdit();
        }

        protected override void PerformFind()
        {
            base.PerformFind();
        }

        /// <summary>
        /// Perform when click print button
        /// </summary>
        protected override void PerformPrint()
        {
            base.PerformPrint();
        }

        /// <summary>
        /// Load data or perform when click refresh button
        /// </summary>
        protected override void PerformRefresh()
        {
            LoadData();

            if (_dtb != null)
            {
                // Binding data
                ClearDataBindings();
                if (_dtb.Rows.Count > 0) DataBindingControl();
            }
            base.PerformRefresh();
        }

        /// <summary>
        /// Perform when click save button
        /// </summary>
        protected override void PerformSave()
        {
            switch (_frmState)
            {
                case UTL.Session.FormState.Add:
                    if (InsertObject())
                    {
                        ResetText(); LoadData();
                    }
                    break;

                case UTL.Session.FormState.Edit:
                    if (UpdateObject())
                    {
                        ChangeStatus(); ReadOnlyControl();
                        PerformRefresh();
                    }
                    break;
            }

            base.PerformSave();
        }

        /// <summary>
        /// Reset all input control
        /// </summary>
        protected override void ResetText()
        {
            lokGuestId.ItemIndex = 0; // none            
            lokRoomId.ItemIndex = 0; // none
            lokLeaseTypeId.ItemIndex = 0; // none

            dteComingDate.EditValue = DAL.BaseDAL.CurrentTime;
            dteLeaveDate.EditValue = null;

            txtOldElec.Text = "0";
            txtNewElec.Text = "0";
            txtPriceElec.Text = _fee.PriceElec + "";

            txtOldWater.Text = "0";
            txtNewWater.Text = "0";
            txtPriceWater.Text = _fee.PriceWater + "";

            base.ResetText();
        }

        /// <summary>
        /// Clear data binding
        /// </summary>
        protected override void ClearDataBindings()
        {
            lokGuestId.DataBindings.Clear();
            lokRoomId.DataBindings.Clear();
            lokLeaseTypeId.DataBindings.Clear();

            dteComingDate.DataBindings.Clear();
            dteLeaveDate.DataBindings.Clear();

            txtOldElec.DataBindings.Clear();
            txtNewElec.DataBindings.Clear();
            txtPriceElec.DataBindings.Clear();

            txtOldWater.DataBindings.Clear();
            txtNewWater.DataBindings.Clear();
            txtPriceWater.DataBindings.Clear();

            base.ClearDataBindings();
        }

        /// <summary>
        /// Add data binding
        /// </summary>
        protected override void DataBindingControl()
        {
            lokGuestId.DataBindings.Add("EditValue", _dtb, ".GuestId");
            lokRoomId.DataBindings.Add("EditValue", _dtb, ".RoomId");
            lokLeaseTypeId.DataBindings.Add("EditValue", _dtb, ".LeaseTypeId");

            dteComingDate.DataBindings.Add("EditValue", _dtb, ".ComingDate");
            dteLeaveDate.DataBindings.Add("EditValue", _dtb, ".LeaveDate");

            txtOldElec.DataBindings.Add("EditValue", _dtb, ".OldElec");
            txtNewElec.DataBindings.Add("EditValue", _dtb, ".NewElec");
            txtPriceElec.DataBindings.Add("EditValue", _dtb, ".PriceElec");

            txtOldWater.DataBindings.Add("EditValue", _dtb, ".OldWater");
            txtNewWater.DataBindings.Add("EditValue", _dtb, ".NewWater");
            txtPriceWater.DataBindings.Add("EditValue", _dtb, ".PriceWater");

            base.DataBindingControl();
        }

        /// <summary>
        /// Set read only control on form
        /// </summary>
        /// <param name="isReadOnly">Read only is trule else normal</param>
        protected override void ReadOnlyControl(bool isReadOnly = true)
        {
            lokGuestId.Properties.ReadOnly = true;
            lokRoomId.Properties.ReadOnly = true;
            lokLeaseTypeId.Properties.ReadOnly = isReadOnly;

            dteComingDate.Properties.ReadOnly = true;
            dteLeaveDate.Properties.ReadOnly = isReadOnly;

            txtOldElec.Properties.ReadOnly = true;
            txtNewElec.Properties.ReadOnly = isReadOnly;
            txtPriceElec.Properties.ReadOnly = true;

            txtOldWater.Properties.ReadOnly = true;
            txtNewWater.Properties.ReadOnly = isReadOnly;
            txtPriceWater.Properties.ReadOnly = true;

            grcMain.Enabled = isReadOnly;

            base.ReadOnlyControl(isReadOnly);
        }

        /// <summary>
        /// Update object
        /// </summary>
        /// <returns>True if successful else false</returns>
        protected override bool UpdateObject()
        {
            try
            {
                if (!ValidInput()) return false;

                var tmp = grvMain.GetFocusedRowCellValue("Id") + "";
                long id = UTL.Number.ToInt64(tmp);

                var o = new DAL.tb_Lease()
                {
                    Id = id,
                    GuestId = UTL.Number.ToInt64(lokGuestId.EditValue + ""),
                    RoomId = UTL.Number.ToInt64(lokRoomId.EditValue + ""),
                    LeaseTypeId = UTL.Number.ToInt64(lokLeaseTypeId.EditValue + ""),
                    UserId = FrmMain._sss.Id,

                    ComingDate = Convert.ToDateTime(dteComingDate.EditValue),

                    OldElec = UTL.Number.ToInt64(txtOldElec.Text),
                    NewElec = UTL.Number.ToInt64(txtNewElec.Text),
                    PriceElec = UTL.Number.ToDecimal(txtPriceElec.Text),

                    OldWater = UTL.Number.ToInt64(txtOldWater.Text),
                    NewWater = UTL.Number.ToInt64(txtNewWater.Text),
                    PriceWater = UTL.Number.ToDecimal(txtPriceWater.Text)
                };
                if (dteLeaveDate.EditValue == null) o.LeaveDate = null;
                else o.LeaveDate = Convert.ToDateTime(dteLeaveDate.EditValue);

                var oki = _bll.Update(o);
                if (oki == UTL.Session.PerState.Duplicate)
                    UTL.Message.Show(STR_DUPLICATE, STR_EDIT);
                return oki == UTL.Session.PerState.Success ? true : false;
            }
            catch { return false; }
        }

        /// <summary>
        /// Delete object
        /// </summary>
        /// <returns>True if successful else false</returns>
        protected override bool InsertObject()
        {
            try
            {
                if (!ValidInput()) return false;

                var o = new DAL.tb_Lease()
                {
                    GuestId = UTL.Number.ToInt64(lokGuestId.EditValue + ""),
                    RoomId = UTL.Number.ToInt64(lokRoomId.EditValue + ""),
                    LeaseTypeId = UTL.Number.ToInt64(lokLeaseTypeId.EditValue + ""),
                    UserId = FrmMain._sss.Id,

                    ComingDate = Convert.ToDateTime(dteComingDate.EditValue),

                    OldElec = UTL.Number.ToInt64(txtOldElec.Text),
                    NewElec = UTL.Number.ToInt64(txtNewElec.Text),
                    PriceElec = UTL.Number.ToDecimal(txtPriceElec.Text),

                    OldWater = UTL.Number.ToInt64(txtOldWater.Text),
                    NewWater = UTL.Number.ToInt64(txtNewWater.Text),
                    PriceWater = UTL.Number.ToDecimal(txtPriceWater.Text)
                };
                if (dteLeaveDate.EditValue == null) o.LeaveDate = null;
                else o.LeaveDate = Convert.ToDateTime(dteLeaveDate.EditValue);

                var oki = _bll.Insert(o);
                if (oki == UTL.Session.PerState.Duplicate)
                    UTL.Message.Show(STR_DUPLICATE, STR_ADD);
                return oki == UTL.Session.PerState.Success ? true : false;
            }
            catch { return false; }
        }

        /// <summary>
        /// Load data
        /// </summary>
        protected override void LoadData()
        {
            lokRoomId.Properties.DataSource = _roo.Select();

            _dtb = _bll.Select();

            if (_dtb != null)
            {
                grcMain.DataSource = _dtb;
                gridColumn2.BestFit(); // fit column
            }

            base.LoadData();
        }

        /// <summary>
        /// Valid data before insert or update to database
        /// </summary>
        /// <returns>True if valid else false</returns>
        protected override bool ValidInput()
        {
            /*if (lokRoomId.Text + "" == "")
            {
                UTL.Message.Show(STR_FULL, STR_ADD);
                lokRoomId.Focus();
                return false;
            }*/

            if (txtNewElec.Text + "" == "")
            {
                UTL.Message.Show("Nhập số điện mới!", STR_ADD);
                txtNewElec.Focus();
                return false;
            }

            if (txtNewWater.Text + "" == "")
            {
                UTL.Message.Show("Nhập số nước mới", STR_ADD);
                txtNewWater.Focus();
                return false;
            }

            return base.ValidInput();
        }
        #endregion
    }
}